/*
 * @Author: wushengran
 * @Date: 2024-06-04 13:58:28
 * @Description: 
 * 
 * Copyright (c) 2024 by atguigu, All Rights Reserved. 
 */
#include "tim3.h"

#define MODE_INPUT                        0
#define MODE_OUTPUT_SPEED_10MHZ           1
#define MODE_OUTPUT_SPEED_2MHZ            2
#define MODE_OUTPUT_SPEED_50MHZ           3

#define CONF_OUTPUT_GENERAL_PUSH_PULL     0
#define CONF_OUTPUT_GENERAL_OPEN_DRAIN    1
#define CONF_OUTPUT_ALTERNATE_PUSH_PULL   2
#define CONF_OUTPUT_ALTERNATE_OPEN_DRAIN  3

#define CONF_INPUT_ANALOG                 0
#define CONF_INPUT_FLOATING               1
#define CONF_INPUT_PULL_UP_DOWN           2
#define CONF_INPUT_RESERVED               3

void TIM3_Init(void)
{
    // 1. 开启时钟
    RCC->APB2ENR |= RCC_APB2ENR_IOPBEN;
    RCC->APB1ENR |= RCC_APB1ENR_TIM3EN;

    // 2. GPIO工作模式，PB0：复用推挽输出 CNF-10，MODE-11
    GPIOB->CRL &= ~(0xF << (0 * 4));
    GPIOB->CRL |= MODE_OUTPUT_SPEED_50MHZ         << (0 * 4);
    GPIOB->CRL |= CONF_OUTPUT_ALTERNATE_PUSH_PULL << (0 * 4 + 2);

    // 3. 定时器配置
    // 3.1 预分频值 7199，得到10000Hz
    TIM3->PSC = 7199;

    // 3.2 重装载值，99，每隔 10ms 溢出一次
    TIM3->ARR = 99;

    // 3.3 计数方向
    TIM3->CR1 &= ~TIM_CR1_DIR;

    // 3.4 设置通道3的CCR值
    TIM3->CCR3 = 0;

    // 3.5 配置通道3为输出模式
    TIM3->CCMR2 &= ~TIM_CCMR2_CC3S;

    // 3.6 配置通道3为PWM1模式，OC3M-110
    TIM3->CCMR2 |= TIM_CCMR2_OC3M_2;
    TIM3->CCMR2 |= TIM_CCMR2_OC3M_1;
    TIM3->CCMR2 &= ~TIM_CCMR2_OC3M_0;

    // 3.7 使能输出通道
    TIM3->CCER |= TIM_CCER_CC3E;
}

// 将定时器的开关包装成函数
void TIM3_Start(void)
{
    TIM3->CR1 |= TIM_CR1_CEN;
}

void TIM3_Stop(void)
{
    TIM3->CR1 &= ~TIM_CR1_CEN;
}

// 设置占空比的函数
void TIM3_SetDutyCycle(uint8_t dutyCycle)
{
    TIM3->CCR3 = dutyCycle;
}
